//
//  PPHTTPRequest.m
//  PPNetworkHelper
//
//  Created by AndyPang on 2017/4/10.
//  Copyright © 2017年 AndyPang. All rights reserved.
//

#define kRequestSuccessCode        1
typedef NS_ENUM(NSInteger, kRequestStatusCode) {
    //非0表示接口执行成功
    RequestFailedStatusCode  =  0,    //请求接口失败
    RequestFailedStatusCodeNotComplete  =  - 1,    //请求参数不完整
//    LoginFailureStatusCode   =  - 5,    //Token无效，重新登陆！
};

#import "PPHTTPRequest.h"
#import "PPNetworkHelper.h"
#import "AppDelegate.h"
#import "AFNetworking.h"

@implementation PPHTTPRequest

#pragma mark - 请求的公共方法
+ (NSURLSessionTask *)requestWithURL:(NSString *)URL parameters:(NSDictionary *)parameter success:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    // 在请求之前你可以统一配置你请求的相关参数 ,设置请求头, 请求参数的格式, 返回数据的格式....这样你就不需要每次请求都要设置一遍相关参数
    // 设置请求头
//    [PPNetworkHelper setValue:@"9" forHTTPHeaderField:@"fromType"];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",BH_Service,URL];
    // 发起请求
    DLog(@"%@",urlStr);
    DLog(@"%@",parameter);
    return [PPNetworkHelper POST:urlStr parameters:parameter success:^(id responseObject) {
        // 在这里你可以根据项目自定义其他一些重复操作,比如加载页面时候的等待效果, 提醒弹窗....
        [self _requestSuccess:success responseObject:responseObject];
    } failure:^(NSError *error) {
        [self _requestFailure:success];
    }];
}

//带缓存请求的公共方法
+ (NSURLSessionTask *)requestCacheWithURL:(NSString *)URL parameters:(NSDictionary *)parameter success:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    // 在请求之前你可以统一配置你请求的相关参数 ,设置请求头, 请求参数的格式, 返回数据的格式....这样你就不需要每次请求都要设置一遍相关参数
    // 设置请求头
    //    [PPNetworkHelper setValue:@"9" forHTTPHeaderField:@"fromType"];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",BH_Service,URL];
    // 发起请求
    return [PPNetworkHelper POST:urlStr parameters:parameter responseCache:^(id responseCache) {
        if (![BHSettingUtil dataAndStringIsNull:responseCache]) {
            NSDictionary *result = (NSDictionary *)responseCache;
            success(result[@"data"], true);
        }
    } success:^(id responseObject) {
        // 在这里你可以根据项目自定义其他一些重复操作,比如加载页面时候的等待效果, 提醒弹窗....
        [self _requestSuccess:success responseObject:responseObject];
    } failure:^(NSError *error) {
        [self _requestFailure:success];
    }];
}

//上传图片
+ (NSURLSessionTask *)requestUploadImagesURL:(NSString *)URL parameters:(id)parameters images:(NSArray *)images success:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    NSString *urlStr;
    if ([URL hasPrefix:@"http://"]) {
        [PPNetworkHelper setResponseSerializer:PPResponseSerializerHTTP];
        urlStr = URL;
    }else {
        urlStr = [NSString stringWithFormat:@"%@%@",BH_Service,URL];
    }
//    return [PPNetworkHelper uploadImagesWithURL:urlStr parameters:parameters name:@"fileImg" images:images fileNames:nil imageScale:0.5 imageType:nil progress:^(NSProgress *progress) {
    return [PPNetworkHelper uploadImagesWithURL:urlStr parameters:parameters name:@"pic" images:images fileNames:nil imageScale:0.5 imageType:nil progress:^(NSProgress *progress) {
    } success:^(id responseObject) {
        DLog(@"%@",responseObject);
        NSDictionary *result = (NSDictionary *)responseObject;
//        if ([result[@"success"] integerValue] == kRequestSuccessCode && [result[@"errcode"] integerValue] == kRequestSuccessCode) {
        if ([result[@"errcode"] integerValue] == kRequestSuccessCode) {
            id obj = result[@"data"];
            if ([obj isKindOfClass:[NSString class]]) {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:result[@"data"],@"image", nil];
                success(dic, true);
            }else {
                success(result[@"data"], true);
            }
        }else {
            success(BHTransient_Data, true);
        }        
    } failure:^(NSError *error) {
        [self _requestFailure:success];
    }];
}

//上传多个图片 文件流
+ (NSURLSessionTask *)requestUploadImagesURL:(NSString *)URL parameters:(id)parameters images:(NSArray *)images  names:(NSArray *)names success:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    NSString *urlStr;
    if ([URL hasPrefix:@"http://"]) {
        [PPNetworkHelper setResponseSerializer:PPResponseSerializerHTTP];
        urlStr = URL;
    }else {
        urlStr = [NSString stringWithFormat:@"%@%@",BH_Service,URL];
    }
//    return [PPNetworkHelper uploadImagesWithURL:urlStr parameters:parameters name:@"pic" images:images fileNames:nil imageScale:0.5 imageType:nil progress:^(NSProgress *progress) {
    return [PPNetworkHelper uploadImagesWithURL:urlStr parameters:parameters nameArray:names imagesArray:images fileNames:nil imageScale:0.5 imageType:nil progress:^(NSProgress *progress) {
    } success:^(id responseObject) {
        DLog(@"%@",responseObject);
        NSDictionary *result = (NSDictionary *)responseObject;
        //        if ([result[@"success"] integerValue] == kRequestSuccessCode && [result[@"errcode"] integerValue] == kRequestSuccessCode) {
        if ([result[@"errcode"] integerValue] == kRequestSuccessCode) {
            id obj = result[@"data"];
            if ([obj isKindOfClass:[NSString class]]) {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:result[@"data"],@"image", nil];
                success(dic, true);
            }else {
                success(result[@"data"], true);
            }
        }else {
            success(BHTransient_Data, true);
        }
    } failure:^(NSError *error) {
        [self _requestFailure:success];
    }];
}

+ (void)requestIdentificationUploadImagesURL:(NSString *)URL parameters:(NSArray *)images success:(PPRequestSuccess)success {
    // 1.创建url  采用Apache本地服务器
    URL = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:URL];
    // 2.创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 文件上传使用post
    request.HTTPMethod = @"POST";
    // 3.开始上传   request的body data将被忽略，而由fromData提供
    NSData *imageData = UIImageJPEGRepresentation(images[0],1);
    [[[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:imageData  completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSLog(@"upload success：%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@,%@",data,dic);
            
        } else {
            NSLog(@"upload error:%@",error);
        }
    }] resume];
    
}

#pragma mark 请求数据失败
+ (void)_requestFailure:(PPRequestSuccess)success {
    [[BHAlertUtil alertManager]hiddenLoading];
    if (![PPNetworkHelper isNetwork]) {
        [[BHAlertUtil alertManager]showPromptInfo:BHTransient_NotNetwork];
        success(BHTransient_NotNetwork, false);
    }else {
        [[BHAlertUtil alertManager]showPromptInfo:@"网络链接失败"];
        success(@"网络连接失败", false);
    }
}

#pragma mark - 请求数据成功
+ (void)_requestSuccess:(PPRequestSuccess)success responseObject:(id)responseObject {
    NSDictionary *result = (NSDictionary *)responseObject;
    DLog(@"%@",result);
//    {
//        data =     {
//        };
//        errcode = 1;
//        errmsg = ok;
//    }
    
    if ([result[@"errcode"] integerValue] == kRequestSuccessCode) {
        if ([result[@"data"] isKindOfClass:[NSArray class]]) {
            NSArray *arr = (NSArray *)result[@"data"];
            if (arr.count == 0) {
                success(BHTransient_Data, true);
            }else success(arr, true);
        }else if ([BHSettingUtil dataAndStringIsNull:result[@"data"]]) {
            success(result[@"errmsg"], true);
        }else success(result[@"data"], true);
    }else {
//        if ([result[@"errcode"] integerValue] == RequestFailedStatusCode) {
//            [[BHAlertUtil alertManager]showPromptInfo:@"获取数据失败"];//请求接口失败
//            success(@"获取数据失败", false);
//        }else if ([result[@"errcode"] integerValue] == LoginFailureStatusCode) {
//            [(AppDelegate *)[UIApplication sharedApplication].delegate gotoLogin:nil];
//            [[BHAlertUtil alertManager]showPromptInfo:@"登录失效请重新登录"];
//            success(@"您还没有登录了", false);
//        }else {
            [[BHAlertUtil alertManager]showPromptInfo:result[@"errmsg"]];
            success(result[@"errmsg"], false);
//        }
    }
}

#pragma mark - 登录
#pragma mark - 登陆退出
//登录
+ (void)requestPostLogins:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Login parameters:params success:result failure:nil];
}
//注册
+ (void)requestPostRegister:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_PostRegister parameters:params success:result failure:nil];
}
//2.3、推广注册 - 认证企业信息及创建展位
+ (void)requestPostBH_User_setUserBooth:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_setUserBooth parameters:params success:result failure:nil];
}
+ (void)requestPostBH_User_setUserBooth:(PPRequestSuccess)result params:(NSDictionary *)params imagesArray:(NSArray *)imagesArray names:(NSArray *)names {
    [self requestUploadImagesURL:BH_User_setUserBooth parameters:params images:imagesArray  names:names success:result failure:nil];
}
//获取验证码
+ (void)requestPostSendCode:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_SendCode parameters:params success:result failure:nil];
}
//找回密码
+ (void)requestPostFindPassword:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_PostFindPassword parameters:params success:result failure:nil];
}
////退出登录
//+ (void)requestPostLogout:(PPRequestSuccess)result params:(NSDictionary *)params;

#pragma mark - 首页
//根据城市ID获取展馆列表
+ (void)requestPostBH_Exhibition_getExhibitionHallByCityId:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getExhibitionHallByCityId parameters:params success:result failure:nil];
}
//根据展馆ID获取展会列表
+ (void)requestPostBH_Exhibition_getExhibitionByHallId:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getExhibitionByHallId parameters:params success:result failure:nil];
}
//获取展会信息列表（各种参数）
+ (void)requestPostBH_Exhibition_getExhibitionList:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getExhibitionList parameters:params success:result failure:nil];
}
//根据展会ID获取布局列表
+ (void)requestPostBH_Exhibition_getExhibitionLayout:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getExhibitionLayout parameters:params success:result failure:nil];
}
//根据布局ID获取企业列表
+ (void)requestPostBH_Exhibition_getCompanyByLayoutId:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getCompanyByLayoutId parameters:params success:result failure:nil];
}
//根据展位ID获取企业详细信息
+ (void)requestPostBH_Exhibition_getCompanyInfoByBoothId:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getCompanyInfoByBoothId parameters:params success:result failure:nil];
}
//根据展位ID获取企业轮播图片
+ (void)requestPostBH_Exhibition_getPicByBoothId:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getPicByBoothId parameters:params success:result failure:nil];
}
//根据企业ID获取产品列表
+ (void)requestPostBH_Exhibition_getProductByCompanyId:(PPRequestSuccess)result params:(NSDictionary *)params{
    [self requestWithURL:BH_Exhibition_getProductByCompanyId parameters:params success:result failure:nil];
}

#pragma mark - 展会

#pragma mark - 企业
//获取企业列表
+ (void)requestPostBH_Company_getCompanyList:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Company_getCompanyList parameters:params success:result failure:nil];
}

#pragma mark - 用户发布及管理操作
//获取用户展位列表
+ (void)requestPostBH_User_getUserBoothList:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_getUserBoothList parameters:params success:result failure:nil];
}
//5.2、企业产品管理
+ (void)requestPostBH_User_getCompanyProduct:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_getCompanyProduct parameters:params success:result failure:nil];
}
//添加产品
+ (void)requestPostBH_User_addProduct:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_addProduct parameters:params success:result failure:nil];
}
+ (void)requestPostBH_User_addProduct:(PPRequestSuccess)result params:(NSDictionary *)params images:(UIImage *)image {
    [self requestUploadImagesURL:BH_User_addProduct parameters:params images:@[image] success:result failure:nil];
}

//编辑产品
+ (void)requestPostBH_User_editProduct:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_editProduct parameters:params success:result failure:nil];
}
+ (void)requestPostBH_User_editProduct:(PPRequestSuccess)result params:(NSDictionary *)params images:(UIImage *)image {
    [self requestUploadImagesURL:BH_User_editProduct parameters:params images:@[image] success:result failure:nil];
}
//删除产品
+ (void)requestPostBH_User_delProduct:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_delProduct parameters:params success:result failure:nil];
}
//企业图片管理
+ (void)requestPostBH_User_getCompanyPic:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_getCompanyPic parameters:params success:result failure:nil];
}
//添加企业图片
+ (void)requestPostBH_User_addCompanyPic:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_addCompanyPic parameters:params success:result failure:nil];
}
+ (void)requestPostBH_User_addCompanyPic:(PPRequestSuccess)result params:(NSDictionary *)params images:(UIImage *)image {
    [self requestUploadImagesURL:BH_User_addCompanyPic parameters:params images:@[image] success:result failure:nil];
}
//删除企业图片
+ (void)requestPostBH_User_delCompanyPic:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_delCompanyPic parameters:params success:result failure:nil];
}
//编辑企业
+ (void)requestPostBH_User_editCompany:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_editCompany parameters:params success:result failure:nil];
}

#pragma mark - 通用查询
//根据城市名称换取城市ID
+ (void)requestPostBH_Region_getRegionId:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Region_getRegionId parameters:params success:result failure:nil];
}
//获取城市列表
+ (void)requestPostBH_RegiongetAllCityes:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_RegiongetAllCityes parameters:params success:result failure:nil];
}
//获取行业分类
+ (void)requestPostBH_Company_getTradeList:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Company_getTradeList parameters:params success:result failure:nil];
}
//获取有展馆的地区
+ (void)requestPostBH_Register_getCitys:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Register_getCitys parameters:params success:result failure:nil];
}

#pragma mark - 首页轮播图
//获取首页轮播图列表
+ (void)requestPostBH_Ads_getSowing:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Ads_getSowing parameters:params success:result failure:nil];
}

#pragma mark - 上传图片
//上传图片
+ (void)requestUploadPicMobile:(PPRequestSuccess)result params:(NSArray *)images; {
    [self requestUploadImagesURL:BH_PicPreString parameters:nil images:images success:result failure:nil];
}

#pragma mark - 注册用户统计
//系统游客与展商数量统计系
+ (void)requestPostBH_User_getSysCount:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_getSysCount parameters:params success:result failure:nil];
}

#pragma mark - 访问足迹
//添加访问足迹
+ (void)requestPostBH_Exhibition_addUserFootPrint:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Exhibition_addUserFootPrint parameters:params success:result failure:nil];
}
//我的访问记录
+ (void)requestPostBH_Exhibition_myFootPrint:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Exhibition_myFootPrint parameters:params success:result failure:nil];
}
//谁看过我的展位
+ (void)requestPostBH_Exhibition_myBoothVisitList:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Exhibition_myBoothVisitList parameters:params success:result failure:nil];
}

#pragma mark - 根据环信账号查询用户基本资料
//根据环信账号查询用户基本资料
+ (void)requestPostBH_User_getUserInfoByHxId:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_User_getUserInfoByHxId parameters:params success:result failure:nil];
}

#pragma mark - 联系官方
//联系官方
+ (void)requestPostBH_Ads_getKefuNumber:(PPRequestSuccess)result params:(NSDictionary *)params {
    [self requestWithURL:BH_Ads_getKefuNumber parameters:params success:result failure:nil];
}

////鉴别
//+ (void)requestUploadUserImg:(PPRequestSuccess)result params:(NSArray *)images {
//    [self requestUploadImagesURL:BH_UploadUserImg parameters:nil images:images success:result failure:nil];
//}

@end
